import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import Highlight from 'react-highlight'
import 'highlight.js/styles/stackoverflow-light.css'; // 使用适合灰色背景的亮色主题

// 防抖函数类型定义
const useDebounce = <T,>(value: T, delay: number): T => {
    const [debouncedValue, setDebouncedValue] = useState<T>(value);

    useEffect(() => {
        const handler = setTimeout(() => {
            setDebouncedValue(value);
        }, delay);

        return () => {
            clearTimeout(handler);
        };
    }, [value, delay]);

    return debouncedValue;
};

// CodeBlock 组件 props 类型定义
interface CodeBlockProps {
    children: string;
    className?: string;
}

export const CodeBlock = ({ children, className }: CodeBlockProps) => {    
    // 获取代码块的语言
    const language = useMemo(() => {
        if (!className) return 'javascript';
        // 支持 language- 和 lang- 前缀
        return className.replace(/^(language-|lang-)/, '') || 'javascript';
    }, [className]);

    // 创建mermaid图表的引用
    const mermaidRef = useRef<HTMLDivElement | null>(null);
    // 创建HTML预览的引用
    const htmlRef = useRef<HTMLDivElement | null>(null);
    // 存储mermaid内容
    const [mermaidContent, setMermaidContent] = useState<string>(children);
    // 存储HTML内容
    const [htmlContent, setHtmlContent] = useState<string>(children);
    // 使用防抖确保内容完整后再渲染
    const debouncedContent = useDebounce(mermaidContent, 800);
    // 使用防抖确保HTML内容完整后再渲染
    const debouncedHtmlContent = useDebounce(htmlContent, 800);
    // 复制状态
    const [copyStatus, setCopyStatus] = useState<string>('复制代码');
    // HTML渲染状态
    const [htmlLoading, setHtmlLoading] = useState<boolean>(true);

    // 当内容变化时更新状态
    useEffect(() => {
        setMermaidContent(children);
        setHtmlContent(children);
        if (language === 'html') {
            setHtmlLoading(true);
        }
    }, [children, language]);

    // 渲染Mermaid图表的函数 - 暂时禁用
    const renderMermaidChart = useCallback(async (content: string) => {
        if (!mermaidRef.current || language !== 'mermaid') return;

        // 暂时显示占位符，避免构建时的依赖问题
        if (mermaidRef.current) {
            mermaidRef.current.innerHTML = '<div class="text-gray-500 p-4 border border-gray-300 rounded">Mermaid 图表功能暂时不可用</div>';
        }
    }, [language]);

    // 使用防抖后的内容进行渲染
    useEffect(() => {
        if (language === 'mermaid' && debouncedContent) {
            renderMermaidChart(debouncedContent);
        }
    }, [debouncedContent, language, renderMermaidChart]);

    // 渲染HTML的函数
    const renderHtml = useCallback(() => {
        if (!htmlRef.current || language !== 'html') return;

        try {
            // 创建一个iframe来安全地执行HTML和JS
            const iframe = document.createElement('iframe');
            iframe.style.width = '100%';
            iframe.style.height = '400px'; // 可根据需要调整高度
            iframe.style.border = 'none';

            // 使用srcdoc属性直接设置HTML内容，避免跨域问题
            iframe.srcdoc = debouncedHtmlContent;

            // 允许执行脚本
            iframe.setAttribute('sandbox', 'allow-scripts');

            // 清除之前的内容
            htmlRef.current.innerHTML = '';
            htmlRef.current.appendChild(iframe);

            // 调整iframe高度以适应内容
            iframe.onload = () => {
                try {
                    // 尝试调整iframe高度
                    setTimeout(() => {
                        try {
                            // 延迟获取高度，确保内容已加载
                            const height = iframe.contentDocument?.body?.scrollHeight || 400;
                            iframe.style.height = `${height + 20}px`; // 添加额外空间
                            setHtmlLoading(false); // 渲染完成
                        } catch (e) {
                            console.log('无法访问iframe内容高度，使用默认高度');
                            setHtmlLoading(false); // 渲染完成，即使有错误
                        }
                    }, 300);
                } catch (e) {
                    console.log('无法设置iframe高度');
                    setHtmlLoading(false); // 渲染完成，即使有错误
                }
            };
        } catch (error) {
            console.error('HTML渲染错误:', error);
            htmlRef.current.innerHTML = '<div class="text-red-500">HTML渲染失败，请检查代码</div>';
            setHtmlLoading(false); // 渲染失败
        }
    }, [debouncedHtmlContent, language]);

    // 使用防抖后的HTML内容进行渲染
    useEffect(() => {
        if (language === 'html' && debouncedHtmlContent) {
            renderHtml();
        }
    }, [debouncedHtmlContent, language, renderHtml]);

    // 判断是否为内联代码
    const isInlineCode = useCallback(() => {
        if (typeof children !== 'string') return false;
        return !children.includes('\n') &&
            !className?.match(/(language-|lang-)/) && 
            children.length < 50;
    }, [children, className]);

    // 处理复制代码
    const handleCopy = async () => {
        try {
            await navigator.clipboard.writeText(children);
            setCopyStatus('已复制!');
            setTimeout(() => setCopyStatus('复制代码'), 2000);
        } catch (err) {
            console.error('Failed to copy:', err);
        }
    };

    // 渲染内联代码
    const renderInlineCode = () => {
        return (
            <span className="bg-[#F9F9F9] px-2 py-1 text-sm font-mono"
                style={{
                    border: '1px solid #eaeaea', borderRadius: '4px',
                    padding: '0.2em 0.4em', fontSize: '85%',
                    fontFamily: 'monospace'
                }}
            >
                <code className={className}>{children}</code>
            </span>
        );
    };

    // 渲染Mermaid块
    const renderMermaidBlock = () => {
        return (
            <div className="mb-4 mt-4">
                <div className="bg-white p-4 border border-gray-200 rounded-md overflow-auto">
                    <div ref={mermaidRef} className="flex justify-center">
                        <div className="text-gray-400">图表正在加载...</div>
                    </div>
                </div>
            </div>
        );
    };

    // 渲染HTML块
    const renderHtmlBlock = () => {
        return (
            <div className="mb-4 mt-4">
                <div className="bg-white p-4 border border-gray-200 rounded-md">
                    <div className="p-4 border border-gray-200 rounded-md">
                        <div className="text-sm text-gray-500 mb-2 flex justify-between items-center">
                            <span>HTML 预览</span>
                            <button
                                onClick={handleCopy}
                                className="px-2 py-1 text-[10px] text-gray-600 hover:bg-gray-100 rounded transition-colors">
                                {copyStatus}
                            </button>
                        </div>
                        {htmlLoading ? (
                            <div className="flex justify-center items-center py-10">
                                <div className="text-gray-400">HTML 内容渲染中...</div>
                            </div>
                        ) : null}
                        <div ref={htmlRef} className="html-preview"></div>
                    </div>
                </div>
            </div>
        );
    };

    // 渲染普通代码块
    const renderStandardCodeBlock = () => {
        return (
            <div className="bg-[#F8F8F8] mb-2 mt-2 rounded-md overflow-x-auto max-w-[350px] border border-gray-200">
                <div className='text-[#666666] p-4 pb-2 pt-2 bg-[#F0F0F0] border-b border-gray-200 flex justify-between'>
                    <span>{language}</span>
                    <button
                        onClick={handleCopy}
                        className="ml-4 px-2 py-1 text-[12px] text-[#666666] hover:bg-[#E0E0E0] rounded transition-colors">
                        {copyStatus}
                    </button>
                </div>
                <div className='p-4 bg-[#F6F6F6]'>
                    <Highlight className={language}>
                        {children}
                    </Highlight>
                </div>
            </div>
        );
    };

    // 主渲染逻辑
    if (isInlineCode()) {
        return renderInlineCode();
    }

    if (language === 'mermaid') {
        return renderMermaidBlock();
    }

    // if (language === 'html') {
    //     return renderHtmlBlock();
    // }

    return renderStandardCodeBlock();
};

